package com.yingeo.pos.mobile;

import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.Setting;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechSynthesizer;
import com.iflytek.cloud.SpeechUtility;
import com.iflytek.cloud.SynthesizerListener;
import com.yingeo.pos.mobile.utils.MLog;

/**
 * @描述 讯飞语音播报SDK Helper
 * @作者 wangweifeng
 * @时间 2017/10/18 0018
 */
public class XunFeiTtsHandler {

    private static final String TAG = "XunFeiVoiceSdkHelper";

    // 讯飞语音合成SDK APPID
    private static final String APP_ID = "59e9ceb9";

    private static XunFeiTtsHandler instance = null;

    // 语音合成对象
    private SpeechSynthesizer mSpeechSynthesizer;

    // 缓冲进度
    private int mPercentForBuffering = 0;
    // 播放进度
    private int mPercentForPlaying = 0;

    // 当前播放的语音文本
    private String mCurrentSpeakText;

    // 当前语音播报发音人
    private String mCurrentSpeakMan = "xiaolin";

    private XunFeiTtsHandler() {
    }

    public static XunFeiTtsHandler getInstance() {
        if (instance == null) {
            synchronized (XunFeiTtsHandler.class) {
                if (instance == null) {
                    instance = new XunFeiTtsHandler();
                }
            }
        }
        return instance;
    }

    public void initSdk(Context context) {
        if (context == null) return;

        SpeechUtility.createUtility(context.getApplicationContext(), "appid=" + APP_ID);

        // 以下语句用于设置日志开关（默认开启），设置成false时关闭语音云SDK日志打印
        Setting.setShowLog(true);

        // 初始化合成对象
        mSpeechSynthesizer = SpeechSynthesizer.createSynthesizer(context, mSpeechSynthesizerInitListener);
    }

    public void startSpeak(String message) {
        if (mSpeechSynthesizer == null) {
            MLog.d(TAG, "语音合成对象未创建，播放失败");
            return;
        }

        this.mCurrentSpeakText = message;

        // 如果当前正在合成播放，停止合成播放
        if (mSpeechSynthesizer.isSpeaking()) {
            mSpeechSynthesizer.stopSpeaking();
        }

        setParam();

        int code = mSpeechSynthesizer.startSpeaking(message, mTtsListener);

        if (code != ErrorCode.SUCCESS) {
            MLog.d(TAG, "语音合成失败,错误码: " + code);
        } else {
            MLog.d(TAG, "语音合成播放成功");
        }
    }

    public void destory() {
        if (null != mSpeechSynthesizer) {
            mSpeechSynthesizer.stopSpeaking();
            // 退出时释放连接
            mSpeechSynthesizer.destroy();
        }
    }

    /**
     * 初始化监听。
     */
    private InitListener mSpeechSynthesizerInitListener = new InitListener() {
        @Override
        public void onInit(int code) {
            MLog.d(TAG, "InitListener init() code = " + code);
            if (code != ErrorCode.SUCCESS) {
                MLog.d(TAG, "初始化失败,错误码：" + code);
            } else {
                MLog.d(TAG, "初始化成功...");
                // 初始化成功，之后可以调用startSpeaking方法
                // 注：有的开发者在onCreate方法中创建完合成对象之后马上就调用startSpeaking进行合成，
                // 正确的做法是将onCreate中的startSpeaking调用移至这里
            }
        }
    };

    private void setParam() {
        // 清空参数
        mSpeechSynthesizer.setParameter(SpeechConstant.PARAMS, null);

        mSpeechSynthesizer.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD);
        // 设置在线合成发音人
        mSpeechSynthesizer.setParameter(SpeechConstant.VOICE_NAME, mCurrentSpeakMan);
        // 设置合成语速
        mSpeechSynthesizer.setParameter(SpeechConstant.SPEED, "50");
        // 设置合成音调
        mSpeechSynthesizer.setParameter(SpeechConstant.PITCH, "50");
        // 设置合成音量
        mSpeechSynthesizer.setParameter(SpeechConstant.VOLUME, "100");
        // 设置播放器音频流类型
        mSpeechSynthesizer.setParameter(SpeechConstant.STREAM_TYPE, "3");
        // 设置播放合成音频打断音乐播放，默认为true
        mSpeechSynthesizer.setParameter(SpeechConstant.KEY_REQUEST_FOCUS, "true");

        // 设置音频保存路径，保存音频格式支持pcm、wav，设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限
        // 注：AUDIO_FORMAT参数语记需要更新版本才能生效
        mSpeechSynthesizer.setParameter(SpeechConstant.AUDIO_FORMAT, "pcm");
        mSpeechSynthesizer.setParameter(SpeechConstant.TTS_AUDIO_PATH, Environment.getExternalStorageDirectory() + "/.msc/tts.pcm");
    }

    /**
     * 合成回调监听。
     */
    private SynthesizerListener mTtsListener = new SynthesizerListener() {

        @Override
        public void onSpeakBegin() {
            MLog.d(TAG, "开始播放");
        }

        @Override
        public void onSpeakPaused() {
            MLog.d(TAG, "暂停播放");
        }

        @Override
        public void onSpeakResumed() {
            MLog.d(TAG, "继续播放");
        }

        @Override
        public void onBufferProgress(int percent, int beginPos, int endPos, String info) {
            // 合成进度
            mPercentForBuffering = percent;
            String result = String.format("缓冲进度为%d%%，播放进度为%d%%", mPercentForBuffering, mPercentForPlaying);
        }

        @Override
        public void onSpeakProgress(int percent, int beginPos, int endPos) {
            // 播放进度
            mPercentForPlaying = percent;
            String result = String.format("缓冲进度为%d%%，播放进度为%d%%", mPercentForBuffering, mPercentForPlaying);
        }

        @Override
        public void onCompleted(SpeechError error) {
            if (error == null) {
                MLog.d(TAG, "播放完成");
            } else if (error != null) {
                MLog.d(TAG, error.getPlainDescription(true));
            }
        }

        @Override
        public void onEvent(int i, int i1, int i2, Bundle bundle) {
            
        }
    };

}
